package com.palmar.proxy.server;

import com.palmar.proxy.configuration.SocksProxyConfiguration;
import com.palmar.proxy.handler.socks.SocksUDPHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class SocksUDPServerStarter extends ProxyStarter {

    private NioEventLoopGroup workerGroup;

    private SocksProxyConfiguration configuration;

    private Bootstrap bootstrap;

    @Override
    protected void init() {
        this.workerGroup = new NioEventLoopGroup();
        this.bootstrap.group(this.workerGroup);
        this.bootstrap.channel(NioDatagramChannel.class);
        this.bootstrap.handler(new SocksUDPHandler());
        try {
            Channel channel = this.bootstrap.bind(1080).sync().channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Channel start() {
        ChannelFuture sync = null;
        try {
            sync = this.bootstrap.bind(this.configuration.udpPort).sync();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            this.workerGroup.shutdownGracefully();
        }
        return sync.channel();
    }
}
